﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using Dapper;
using DapperExtensions;
using ExaminationSys.DataAccess.Entity;
using SQLinq;
using SQLinq.Dapper;

namespace ExaminationSys.DataAccess.Repository
{
    public class DBQuestionRepository : Repository<DBQuestion>
    {
        public DBQuestionRepository(SqlConnection context)
            : base(context)
        {
            db = context;
        }
        private SqlConnection db;
        public override DBQuestion GetById(dynamic id)
        {
            return base.ObjectSet.Get<DBQuestion>(db, id, null, null);
        }
    }

    public class DBQuestionService
    {
        private DBQuestionService()
        {
        }

        public DBQuestion Get(Guid id)
        {
            using (var db = DataContent.DBServer())
            {
                IUnitOfWork work = new UnitOfWork(db);
                var result = work.DBQuestion.GetById(id);
                return result;

            }
        }

        public bool CheckContent(string content, string dbquestiontype)
        {
            using (var db = DataContent.DBServer())
            {
                var pg = new PredicateGroup { Operator = GroupOperator.And, Predicates = new List<IPredicate>() };
                pg.Predicates.Add(Predicates.Field<DBQuestion>(f => f.Content, Operator.Eq, content));
                pg.Predicates.Add(Predicates.Field<DBQuestion>(f => f.DBQuestionType, Operator.Eq, dbquestiontype));
                IUnitOfWork work = new UnitOfWork(db);
                var result = work.DBQuestion.GetList(pg).FirstOrDefault();
                return result != null;
            }
        }

        public string GetSerialNo(string strWhere)
        {
            using (var db = DataContent.DBServer())
            {
                var obj = new
                {
                    TableName = "DBQuestion",
                    Fields = "SerialNo",
                    OrderField = "SerialNo DESC",
                    sqlWhere = string.Format(" SerialNo like '%{0}%'", strWhere),
                    pageSize = 1,
                    pageIndex = 1,
                };

                var dynamicParam = new DynamicParameters(obj);
                dynamicParam.Add("TotalPage", null, DbType.Int32, ParameterDirection.Output, 32);
                dynamicParam.Add("TotalRecord", 0, DbType.Int32, ParameterDirection.Output, 32);

                var items = db.Query<DBQuestion>("PagingRecord", dynamicParam, null, true, null, CommandType.StoredProcedure);
                List<DBQuestion> list = items.ToList();
                if (list != null && list.Count > 0)
                {
                    DBQuestion model = list[0];
                    if (model != null)
                    {
                        string temp = model.SerialNo;
                        if (temp != null && temp.Length > 8)
                        {
                            string str1 = model.SerialNo.Substring(0, 8);
                            string str2 = model.SerialNo.Substring(8);
                            int n = int.Parse(str2);
                            if (n < 9999)
                            {
                                string str = (n + 1).ToString();
                                str = SetStringLenght(str, 4);
                                return str1 + str;
                            }
                        }
                    }
                }
                return strWhere + "0001";
            }
        }
        /// <summary>
        /// 指定长度字符串 不足补"0"
        /// </summary>
        /// <param name="orig">目标字符串</param>
        /// <param name="lenght">长度</param>
        /// <returns>指定长字符串</returns>
        private string SetStringLenght(string orig, int lenght)
        {
            string temp = string.Empty;
            if (!string.IsNullOrEmpty(orig))
            {
                byte[] bs = Encoding.Unicode.GetBytes(orig);
                int lx = bs.Length / 2;
                if (lx != lenght)
                {
                    int ly = lenght - lx;
                    if (ly > 0)
                    {
                        for (int i = 0; i < ly; i++)
                        {
                            temp += "0";
                        }
                        temp += Encoding.Unicode.GetString(bs, 0, lx * 2);
                    }
                    else if (ly < 0)
                    {
                        temp = Encoding.Unicode.GetString(bs, 0, lenght * 2);
                    }
                }
                else { temp = orig; }
            }
            else
            {
                for (int i = 0; i < lenght; i++)
                {
                    temp += "0";
                }
            }
            return temp;
        }

        public List<DBQuestion> GetAll()
        {
            using (var db = DataContent.DBServer())
            {
                IUnitOfWork work = new UnitOfWork(db);
                var result = work.DBQuestion.GetList();
                return result.ToList();
            }
        }

        public List<DBQuestion> GetAll(PaperDetailAuto paperDetailAuto)
        {
            using (var db = DataContent.DBServer())
            {
                StringBuilder sb = new StringBuilder("select * from DBQuestion where ");
                sb.AppendFormat("Challenge='{0}' and Stage='{1}' and KeyWord like '%{2}%'",
                    PaperDetailAuto.Challenge[paperDetailAuto.Degree],
                    PaperDetailAuto.Stage[paperDetailAuto.Level],
                    paperDetailAuto.KeyWrods ?? "");
                sb.Append(" order by SerialNo");

                var items = db.Query<DBQuestion>(sb.ToString());
                return items.ToList();
            }
        }

        public int GetEixstsed(List<DBQuestion> exitDBQuestion, PaperDetailAuto paperDetailAuto)
        {
            int result = 0;

            foreach (DBQuestion dBQuestion in exitDBQuestion)
            {
                if (dBQuestion.Challenge == PaperDetailAuto.Challenge[paperDetailAuto.Degree]
                    && dBQuestion.Stage == PaperDetailAuto.Stage[paperDetailAuto.Level]
                    && (dBQuestion.KeyWord.Contains(paperDetailAuto.KeyWrods) || string.IsNullOrEmpty(paperDetailAuto.KeyWrods)))
                    result++;
            }

            return result;
        }

        public List<DBQuestion> GetPaperExitDBQuestion(string TestHistoryID)
        {
            using (var db = DataContent.DBServer())
            {
                StringBuilder sb = new StringBuilder("select dbq.* from DBQuestion dbq ");
                sb.AppendFormat("join StudentTestQuestion stq on stq.TestHistoryID='{0}' and stq.QuestionID=dbq.ID ",
                    TestHistoryID);
                var items = db.Query<DBQuestion>(sb.ToString());
                return items.ToList();
            }
        }

        public bool Delete(List<string> ids)
        {
            if (ids == null || ids.Count == 0) return false;
            bool flag = false;
            using (var db = DataContent.DBServer())
            {
                int retCode = 0;
                foreach (var id in ids)
                {
                    retCode = db.Execute(@"delete from DBQuestion where ID=@TmpId",
                                         new[] { new { TmpId = id } });
                    if (retCode <= 0)
                    {
                        break;
                    }
                }
                flag = true;
            }
            return flag;
        }

        public bool Lock(List<string> ids, int _lock)
        {
            if (ids == null || ids.Count == 0) return false;
            bool flag = false;
            using (var db = DataContent.DBServer())
            {
                int retCode = 0;
                foreach (var id in ids)
                {
                    retCode = db.Execute(@"update DBQuestion set Lock=@lk where ID=@TmpId",
                                         new[] { new { lk = _lock, TmpId = id } });
                    if (retCode <= 0)
                    {
                        break;
                    }
                }
                flag = true;
            }
            return flag;
        }

        public bool Update(DBQuestion entity)
        {
            using (var db = DataContent.DBServer())
            {
                IUnitOfWork work = new UnitOfWork(db);
                return work.DBQuestion.Update(entity);
            }
        }
        public dynamic Insert(DBQuestion entity)
        {
            using (var db = DataContent.DBServer())
            {
                IUnitOfWork work = new UnitOfWork(db);
                return work.DBQuestion.Insert(entity, null);
            }
        }

        public List<DBQuestion> GetListByPage(string sqlwhere, string orderbyFiled, int pagesize, int pageindex, out int totalPage, out int totalRecord)
        {
            if (string.IsNullOrWhiteSpace(orderbyFiled))
                throw new ArgumentNullException("orderbyFiled");

            if (string.IsNullOrWhiteSpace(sqlwhere))
                sqlwhere = " 1=1";
            using (var db = DataContent.DBServer())
            {
                var obj = new
                {
                    TableName = "DBQuestion",
                    Fields = "*",
                    OrderField = orderbyFiled,
                    sqlWhere = sqlwhere,
                    pageSize = pagesize,
                    pageIndex = pageindex,
                };

                var dynamicParam = new DynamicParameters(obj);
                dynamicParam.Add("TotalPage", null, DbType.Int32, ParameterDirection.Output, 32);
                dynamicParam.Add("TotalRecord", 0, DbType.Int32, ParameterDirection.Output, 32);

                var items = db.Query<DBQuestion>("PagingRecord", dynamicParam, null, true, null, CommandType.StoredProcedure);
                totalPage = dynamicParam.Get<int>("TotalPage");
                totalRecord = dynamicParam.Get<int>("TotalRecord");
                return items.ToList();
            }
        }

        public List<DBQuestion> GetListByPageByView(string sqlwhere, string orderbyFiled, int pagesize, int pageindex, out int totalPage, out int totalRecord)
        {
            if (string.IsNullOrWhiteSpace(orderbyFiled))
                throw new ArgumentNullException("orderbyFiled");

            if (string.IsNullOrWhiteSpace(sqlwhere))
                sqlwhere = " 1=1";
            using (var db = DataContent.DBServer())
            {
                var obj = new
                {
                    TableName = "View_DBSubjectDBQuestion",
                    Fields = "*",
                    OrderField = orderbyFiled,
                    sqlWhere = sqlwhere,
                    pageSize = pagesize,
                    pageIndex = pageindex,
                };

  
                var dynamicParam = new DynamicParameters(obj);
                dynamicParam.Add("TotalPage", null, DbType.Int32, ParameterDirection.Output, 32);
                dynamicParam.Add("TotalRecord", 0, DbType.Int32, ParameterDirection.Output, 32);

                var items = db.Query<DBQuestion>("PagingRecord", dynamicParam, null, true, null, CommandType.StoredProcedure);
                totalPage = dynamicParam.Get<int>("TotalPage");
                totalRecord = dynamicParam.Get<int>("TotalRecord");
                return items.ToList();
            }
        }

        public List<DBQuestion> GetListPageByView(string sqlwhere, string orderbyFiled, int pagesize, int pageindex, out int totalPage, out int totalRecord)
        {
            if (string.IsNullOrWhiteSpace(orderbyFiled))
                throw new ArgumentNullException("orderbyFiled");

            if (string.IsNullOrWhiteSpace(sqlwhere))
                sqlwhere = " 1=1";
            using (var db = DataContent.DBServer())
            {
                var obj = new
                {
                    TableName = "View_DBSubjectQuestion",
                    Fields = "*",
                    OrderField = orderbyFiled,
                    sqlWhere = sqlwhere,
                    pageSize = pagesize,
                    pageIndex = pageindex,
                };

                var dynamicParam = new DynamicParameters(obj);
                dynamicParam.Add("TotalPage", null, DbType.Int32, ParameterDirection.Output, 32);
                dynamicParam.Add("TotalRecord", 0, DbType.Int32, ParameterDirection.Output, 32);

                var items = db.Query<DBQuestion>("PagingRecord", dynamicParam, null, true, null, CommandType.StoredProcedure);
                totalPage = dynamicParam.Get<int>("TotalPage");
                totalRecord = dynamicParam.Get<int>("TotalRecord");
                return items.ToList();
            }
        }


        public Int32 LoadColumns(string filepath, string sheetName)
        {
            string strFileName = Path.GetExtension(filepath).ToLower();
            Int32 addcount = 0;

            #region Data

            string strConn;
            if (strFileName == ".xls")
            {

                strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath +
                          ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1;\";";
            }
            else
            {
                strConn =
                    string.Format(
                        "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'",
                        filepath);
            }

            #endregion

            using (OleDbConnection conn = new OleDbConnection(strConn))
            {
                conn.Open();
                var ds = new DataSet();
                var oada = new OleDbDataAdapter(string.Format("select * from [{0}]", sheetName), strConn);
                oada.Fill(ds);
                if (ds.Tables.Count > 0)
                {
                    string strWhere = DateTime.Now.ToString("yyyyMMdd");
                    bool sucess = false;
                    List<string> errorList=new List<string>();

                    foreach (DataRow row in ds.Tables[0].Rows)
                    {
                        if (!Check(row, ref errorList))
                            break;
                        List<List<object>> list = GetDBAnswer(row);
                        if (list != null && list.Count > 0)
                        {
                            int answercount = list.Count;
                            int rightanswercount = GetDBAnswerCount(list);
                            string subjecttype = row.Field<string>("类型");
                            bool addflag = false;

                            if (subjecttype.Equals("多选") && answercount > 2 && rightanswercount > 1)
                                addflag = true;
                            else if (subjecttype.Equals("单选") && answercount > 1 && rightanswercount == 1)
                                addflag = true;
                            if (addflag && !CheckContent(row.Field<string>("题目"), "普通题"))
                            {
                                DBQuestion entity = new DBQuestion();
                                entity.ID = Guid.NewGuid();
                                entity.SerialNo = GetSerialNo(strWhere);
                                entity.Content = row.Field<string>("题目");
                                entity.QuestionType = row.Field<string>("类型");
                                entity.SubjectType = subjecttype;
                                entity.DBQuestionType = "普通题";
                                entity.KeyWord = row.Field<string>("关键字");
                                entity.Knowledge = row.Field<string>("知识点");
                                entity.Challenge = row.Field<string>("难度");
                                entity.Point = Decimal.Parse(row.Field<double>("分值").ToString());
                                entity.AttachFile = row.Field<string>("附件");
                                entity.Title = "";
                                entity.Stage = row.Field<string>("阶段");
                                entity.Status = 1;
                                entity.AddTime = DateTime.Now;
                                entity.Lock = false;
                                entity.Operator = "admin";
                                entity.OperatorTime = DateTime.Now;

                                var retCode = Insert(entity);
                                sucess = retCode != null;
                                sucess = DBAnswerAdd(sucess, entity.ID, list);
                                if (sucess)
                                    addcount++;
                            }
                        }
                    }
                }
            }
            return addcount;
        }

        private bool Check(DataRow row, ref List<string> errorList)
        {
            bool right = true;
            #region 条件

            //if (string.IsNullOrWhiteSpace(row.Field<string>("关键字")))
            //{
            //    errorList.Add("关键字不能为空");
            //    right = false;
            //}
            //if (string.IsNullOrWhiteSpace(row.Field<string>("知识点")))
            //{
            //    errorList.Add("知识点不能为空");
            //    right = false;
            //}
            if (string.IsNullOrEmpty(row.Field<string>("类型")))
            {
                errorList.Add("类型不能为空");
                right = false;
            }
            if (string.IsNullOrEmpty(row.Field<string>("题型")))
            {
                errorList.Add("题型不能为空");
                right = false;
            }
            if (string.IsNullOrEmpty(row.Field<string>("难度")))
            {
                errorList.Add("难度不能为空");
                right = false;
            }
            if (string.IsNullOrEmpty(row.Field<string>("阶段")))
            {
                errorList.Add("阶段不能为空");
                right = false;
            }
            if (!(row.Field<double>("分值") > 0))
            {
                errorList.Add("分值必须大于零");
                right = false;
            }
            if (string.IsNullOrEmpty(row.Field<string>("题目")))
            {
                errorList.Add("内容题目不能为空");
                right = false;
            }
            if (!string.IsNullOrEmpty(row.Field<string>("题型"))
                && row.Field<string>("题型").Equals("视听") && string.IsNullOrEmpty(row.Field<string>("附件")))
            {
                errorList.Add("视听题，视听附件不能为空");
                right = false;
            }

            #endregion

            return right;
        }
        public List<List<object>> GetDBAnswer(DataRow row)
        {
            List<List<object>> list = new List<List<object>>();
            if (row != null)
            {
                if (row.Field<string>("选项A") != null && row.Field<string>("选项A").Trim().Length > 0)
                {
                    List<object> listA = new List<object>();
                    listA.Add("A");
                    listA.Add(row.Field<string>("选项A"));
                    if (row.Field<string>("选项A正确") != null && row.Field<string>("选项A正确").Trim().Equals("是"))
                        listA.Add("true");
                    else
                        listA.Add("false");
                    list.Add(listA);
                }
                if (row.Field<string>("选项B") != null && row.Field<string>("选项B").Trim().Length > 0)
                {
                    List<object> listB = new List<object>();
                    listB.Add("B");
                    listB.Add(row.Field<string>("选项B"));
                    if (row.Field<string>("选项B正确") != null && row.Field<string>("选项B正确").Trim().Equals("是"))
                        listB.Add(true);
                    else
                        listB.Add(false);
                    list.Add(listB);
                }
                if (row.Field<string>("选项C") != null && row.Field<string>("选项C").Trim().Length > 0)
                {
                    List<object> listC = new List<object>();
                    listC.Add("C");
                    listC.Add(row.Field<string>("选项C"));
                    if (row.Field<string>("选项C正确") != null && row.Field<string>("选项C正确").Trim().Equals("是"))
                        listC.Add("true");
                    else
                        listC.Add("false");
                    list.Add(listC);
                }
                if (row.Field<string>("选项D") != null && row.Field<string>("选项D").Trim().Length > 0)
                {
                    List<object> listD = new List<object>();
                    listD.Add("D");
                    listD.Add(row.Field<string>("选项D"));
                    if (row.Field<string>("选项D正确") != null && row.Field<string>("选项D正确").Trim().Equals("是"))
                        listD.Add("true");
                    else
                        listD.Add("false");
                    list.Add(listD);
                }
                if (row.Field<string>("选项E") != null && row.Field<string>("选项E").Trim().Length > 0)
                {
                    List<object> listE = new List<object>();
                    listE.Add("E");
                    listE.Add(row.Field<string>("选项E"));
                    if (row.Field<string>("选项E正确") != null && row.Field<string>("选项E正确").Trim().Equals("是"))
                        listE.Add("true");
                    else
                        listE.Add("false");
                    list.Add(listE);
                }
            }
            return list;
        }

        public int GetDBAnswerCount(List<List<object>> list)
        {
            int right = 0;
            if (list != null && list.Count > 0)
            {
                foreach (List<object> tlist in list)
                {
                    if ("true".Equals(tlist[2].ToString()))
                        right++;
                }
            }
            return right;
        }

        public bool DBAnswerAdd(bool sucess,Guid id, List<List<object>> list)
        {
            if (sucess)
            {
                sucess = DBAnswerAdd2(id, list);
                if (!sucess)
                {
                    List<string> idlist = new List<string>();
                    idlist.Add(id.ToString());
                    Delete(idlist);
                }
            }
            return sucess;
        }
        public bool DBAnswerAdd2(Guid id, List<List<object>> list)
        {
            DBAnswerService ProxyDBAnswer = ObjectFactory<DBAnswerService>.Create();
            if (list != null && list.Count > 0)
            {
                List<string> listDelete = new List<string>();
                try
                {
                    DBAnswer dbanswer = new DBAnswer();
                    dbanswer.Lock = false;
                    dbanswer.Status = 1;
                    dbanswer.OperatorTime = DateTime.Now;
                    dbanswer.Operator = "admin";
                    dbanswer.DBQuestionID = id;

                    foreach (List<object> templist in list)
                    {
                        dbanswer.ID = Guid.NewGuid();
                        dbanswer.Prefix = templist[0].ToString();
                        dbanswer.Content = templist[1].ToString();
                        dbanswer.IsRight = "true".Equals(templist[2].ToString());
                        ProxyDBAnswer.Insert(dbanswer);
                        listDelete.Add(dbanswer.ID.ToString());
                    }
                    
                    return true;
                }
                catch (Exception ex)
                {
                    ProxyDBAnswer.Delete(listDelete);
                }
            }
            return false;
        }



        public bool AnswerAddOrUpdate(DBQuestion dBquestion, List<DBAnswer> listanswer, bool addFlag, DBSubjectQuestion dBSubjectQuestion)
        {
            bool flag;

            using (var db = DataContent.DBServer())
            {
                var trans = db.BeginTransaction();
                try
                {
                    if (addFlag)
                    {
                        int retCode = db.Execute(@"insert into DBSubjectQuestion(ID, 
                                DBSubjectID, DBQuestionID, Operator, OperatorTime, Status, Lock, OrderIndex)
                                values(@ID, @DBSubjectID, @DBQuestionID, @Operator, @OperatorTime, @Status, @Lock,@OrderIndex)",
                                new[] { new { ID = dBSubjectQuestion.ID, DBSubjectID=dBSubjectQuestion.DBSubjectID, 
                                    DBQuestionID=dBSubjectQuestion.DBQuestionID, Operator=dBquestion.Operator, 
                                    OperatorTime=dBSubjectQuestion.OperatorTime, Status=dBSubjectQuestion.Status, 
                                    Lock=dBSubjectQuestion.Lock,OrderIndex=dBSubjectQuestion.OrderIndex } },
                                trans);
                        if (retCode <= 0)
                        {
                            flag = false;
                            throw new Exception("error");
                        }

                        retCode = db.Execute(@"insert into DBQuestion(ID, SerialNo, Knowledge, 
                                KeyWord, Stage, QuestionType, DBQuestionType, SubjectType, Challenge, 
                                Point, Title, AttachFile, Content, AddTime, Operator, 
                                OperatorTime, Status, Lock,OrderIndex) 
                                values(@ID, @SerialNo, @Knowledge, 
                                @KeyWord, @Stage, @QuestionType, @DBQuestionType, @SubjectType, @Challenge, 
                                @Point, @Title, @AttachFile, @Content, @AddTime, @Operator, 
                                @OperatorTime, @Status, @Lock,@OrderIndex)",
                                new[] { new { ID=dBquestion.ID,SerialNo=dBquestion.SerialNo, 
                                Knowledge=dBquestion.Knowledge, KeyWord=dBquestion.KeyWord, 
                                Stage=dBquestion.Stage, QuestionType=dBquestion.QuestionType, 
                                DBQuestionType=dBquestion.DBQuestionType, 
                                SubjectType=dBquestion.SubjectType, Challenge=dBquestion.Challenge, 
                                Point=dBquestion.Point, Title=dBquestion.Title, 
                                AttachFile=dBquestion.AttachFile, Content=dBquestion.Content, 
                                AddTime=dBquestion.AddTime, 
                                Operator=dBquestion.Operator, OperatorTime=dBquestion.OperatorTime, 
                                Status=dBquestion.Status, Lock=dBquestion.Lock,OrderIndex=dBquestion.OrderIndex} },
                                trans);
                        if (retCode <= 0)
                        {
                            flag = false;
                            throw new Exception("error");
                        }
                    }
                    else
                    {
                        int retCode = db.Execute(@"update DBSubjectQuestion set
                                Operator=@Operator, OperatorTime=@OperatorTime, OrderIndex=@OrderIndex
                                where DBSubjectID=@DBSubjectID and DBQuestionID=@DBQuestionID",
                                new[] { new { Operator=dBquestion.Operator, OperatorTime=dBSubjectQuestion.OperatorTime, 
                                    OrderIndex=dBSubjectQuestion.OrderIndex,
                                    DBSubjectID=dBSubjectQuestion.DBSubjectID, DBQuestionID = dBSubjectQuestion.DBQuestionID } },
                                trans);
                        if (retCode <= 0)
                        {
                            flag = false;
                            throw new Exception("error");
                        }
                        retCode = db.Execute(@"update DBQuestion set SerialNo=@SerialNo, 
                                Knowledge=@Knowledge, KeyWord=@KeyWord, Stage=@Stage, QuestionType=@QuestionType,  
                                DBQuestionType=@DBQuestionType, SubjectType=@SubjectType, Challenge=@Challenge, 
                                Point=@Point, Title=@Title, AttachFile=@AttachFile, Content=@Content, 
                                AddTime=@AddTime, Operator=@Operator, OperatorTime=@OperatorTime, 
                                Status=@Status, Lock=@Lock,OrderIndex=@OrderIndex 
                                where ID=@ID",
                                new[] { new { SerialNo=dBquestion.SerialNo, 
                                Knowledge=dBquestion.Knowledge, KeyWord=dBquestion.KeyWord, 
                                Stage=dBquestion.Stage, QuestionType=dBquestion.QuestionType, 
                                DBQuestionType=dBquestion.DBQuestionType, 
                                SubjectType=dBquestion.SubjectType, Challenge=dBquestion.Challenge, 
                                Point=dBquestion.Point, Title=dBquestion.Title, 
                                AttachFile=dBquestion.AttachFile, Content=dBquestion.Content, 
                                AddTime=dBquestion.AddTime, Operator=dBquestion.Operator, 
                                OperatorTime=dBquestion.OperatorTime,Status=dBquestion.Status,  
                                Lock=dBquestion.Lock,ID=dBquestion.ID,OrderIndex=dBquestion.OrderIndex } },
                                trans);
                        if (retCode <= 0)
                        {
                            flag = false;
                            throw new Exception("error");
                        }
                    }
                    int retCode2 = db.Execute("delete from DBAnswer where DBQuestionID=@DBQuestionID;",
                        new[] { new { DBQuestionID = dBquestion.ID } }, trans);
                    //if (retCode2 <= 0)
                    //{
                    //    flag = false;
                    //    throw new Exception("error");
                    //}

                    foreach (DBAnswer item in listanswer)
                    {
                        int retCode = db.Execute(@"insert into DBAnswer(ID, DBQuestionID, Prefix, Content, 
                                IsRight, Operator, OperatorTime, Status, Lock) 
                                values(@ID, @DBQuestionID, @Prefix, @Content, 
                                @IsRight, @Operator, @OperatorTime, @Status, @Lock)",
                                new[] { new { ID=item.ID, DBQuestionID=item.DBQuestionID, 
                                    Prefix=item.Prefix, Content=item.Content, IsRight=item.IsRight, 
                                    Operator=item.Operator, OperatorTime=item.OperatorTime, 
                                    Status=item.Status, Lock=item.Lock } },
                                trans);
                        if (retCode <= 0)
                        {
                            flag = false;
                            throw new Exception("error");
                        }
                    }
                    trans.Commit();
                    flag = true;
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    flag = false;
                }
            }
            return flag;
        }
    }
}